<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      .main {
        background-color: black;
        left: 0px;
        height: 500px;
        width: 800px;
        position: relative;
        overflow: hidden;
      }
      .cont {
        white-space: nowrap;
        line-height: 40px;
        color: #fff;
        font-size: 30px;
        position: absolute;
        left: 800px;
      }
    </style>
    <script src="./socket.io.js"></script>
  </head>

  <body>
    <h1>弹幕测试</h1>
    <div class="main"></div>
    <input type="text" name="" id="myinput" />颜色：<input
      type="color"
      value="#ffffff"
      id="color"
    /><br />
    <button>点击发送弹幕</button>

    <script>
      let socket = io.connect();
      let myinput = document.querySelector("#myinput");
      let color = document.querySelector("#color");
      let btn = document.querySelector("button");
      let ulEle = document.querySelector(".main");

      btn.onclick = function () {
        let max = document.querySelectorAll(".cont").length;
        let num = Math.floor(Math.random() * 400) + "px";
        let val = { cont: myinput.value, color: color.value, num };
        if (max <= 20) {
          socket.emit("myval", val);
        }
      };

      socket.on("mymessage", (e) => {
        move(e);
      });

      function move(val) {
        let boxEle = document.createElement("div");
        boxEle.classList = "cont";
        boxEle.style.top = val.num;
        boxEle.innerHTML = val.cont;
        boxEle.style.color = val.color;
        ulEle.appendChild(boxEle);
        
        let timer = setInterval(function () {
          let num = parseInt(getComputedStyle(boxEle)["left"]);
          let width = parseInt(getComputedStyle(boxEle)["width"]);
          if (num <= -width) {
            clearInterval(timer);
            boxEle.remove();
          } else {
            boxEle.style.left = num - 2 + "px";
          }
        }, 20);
      }
    </script>
  </body>
</html>
